package com.tensquare.friend.controller;

import com.tensquare.friend.client.UserClient;
import com.tensquare.friend.service.FriendService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: hjk
 * @Date: 2019/6/23 11:37
 * @Description:
 */
@RestController
@RequestMapping("/friend")
public class FriendController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private FriendService friendService;

    @Autowired
    private UserClient userClient;

    /**
     * 添加好友
     * @param friendId
     * @param type
     * @return
     */
    @PostMapping("/like/{friendId}/{type}")
    public Result addFriend(@PathVariable("friendId") String friendId,@PathVariable("type") String type){
        // 验证是否登陆
        Claims claims= (Claims) request.getAttribute("claims_user");
        if(claims == null){
            return new Result(false,StatusCode.ACCESSERROR,"token fail");
        }
        //得到当前登陆的用户id
        String userId = claims.getId();
        //判断是添加好友还是非好友
        int count = friendService.addFriend(userId,friendId);
        if(count == 0){
            return new Result(false, StatusCode.ERROR,"不能重复添加好友");
        }
        if(count == 1){
            userClient.updatefanscountandfollowcount(userId,friendId,1);
            return new Result(true, StatusCode.OK,"添加好友成功");
        }
        if(!StringUtils.isEmpty(type)){
            if(StringUtils.equals("1",type)){
                //添加好友
            }else if(StringUtils.equals("2",type)){
                //添加非好友
                friendService.addNoFriend(userId,friendId);
            }
            if(count == 0){
                return new Result(false, StatusCode.ERROR,"不能重复添加好友");
            }
            if(count == 1){
                return new Result(true, StatusCode.OK,"添加非好友成功");
            }
            return null;
        }else {
            return new Result(false, StatusCode.ERROR,"参数异常");
        }
    }

    @DeleteMapping("/{friendId}")
    public Result deleteFriend(@PathVariable("friendId") String friendId){
        // 验证是否登陆
        Claims claims= (Claims) request.getAttribute("claims_user");
        if(claims == null){
            return new Result(false,StatusCode.ACCESSERROR,"token fail");
        }
        //得到当前登陆的用户id
        String userId = claims.getId();
        friendService.deleteFriend(userId,friendId);
        userClient.updatefanscountandfollowcount(userId,friendId,-1);
        return new Result(true, StatusCode.OK,"删除好友成功");
    }

}
